3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 use MediaWiki\Logger\LoggerFactory
;
22 use MediaWiki\MediaWikiServices
;
23 use Wikimedia\ScopedCallback
;
26 * Prepare an edit in shared cache so that it can be reused on edit
28 * This endpoint can be called via AJAX as the user focuses on the edit
29 * summary box. By the time of submission, the parse may have already
30 * finished, and can be immediately used on page save. Certain parser
31 * functions like {{REVISIONID}} or {{CURRENTTIME}} may cause the cache
32 * to not be used on edit. Template and files used are check for changes
33 * since the output was generated. The cache TTL is also kept low for sanity.
38 class ApiStashEdit
extends ApiBase
{
39 const ERROR_NONE
= 'stashed';
40 const ERROR_PARSE
= 'error_parse';
41 const ERROR_CACHE
= 'error_cache';
42 const ERROR_UNCACHEABLE
= 'uncacheable';
43 const ERROR_BUSY
= 'busy';
45 const PRESUME_FRESH_TTL_SEC
= 30;
46 const MAX_CACHE_TTL
= 300; // 5 minutes
47 const MAX_SIGNATURE_TTL
= 60;
49 const MAX_CACHE_RECENT
= 2;
51 public function execute() {
52 $user = $this->getUser();
53 $params = $this->extractRequestParams();
55 if ( $user->isBot() ) { // sanity
56 $this->dieWithError( 'apierror-botsnotsupported' );
59 $cache = ObjectCache
::getLocalClusterInstance();
60 $page = $this->getTitleOrPageId( $params );
61 $title = $page->getTitle();
63 if ( !ContentHandler
::getForModelID( $params['contentmodel'] )
64 ->isSupportedFormat( $params['contentformat'] )
67 [ 'apierror-badformat-generic', $params['contentformat'], $params['contentmodel'] ],
72 $this->requireOnlyOneParameter( $params, 'stashedtexthash', 'text' );
76 if ( $params['stashedtexthash'] !== null ) {
77 // Load from cache since the client indicates the text is the same as last stash
78 $textHash = $params['stashedtexthash'];
79 if ( !preg_match( '/^[0-9a-f]{40}$/', $textHash ) ) {
80 $this->dieWithError( 'apierror-stashedit-missingtext', 'missingtext' );
82 $textKey = $cache->makeKey( 'stashedit', 'text', $textHash );
83 $text = $cache->get( $textKey );
84 if ( !is_string( $text ) ) {
85 $this->dieWithError( 'apierror-stashedit-missingtext', 'missingtext' );
88 // 'text' was passed. Trim and fix newlines so the key SHA1's
89 // match (see WebRequest::getText())
90 $text = rtrim( str_replace( "\r\n", "\n", $params['text'] ) );
91 $textHash = sha1( $text );
94 $textContent = ContentHandler
::makeContent(
95 $text, $title, $params['contentmodel'], $params['contentformat'] );
97 $page = WikiPage
::factory( $title );
98 if ( $page->exists() ) {
99 // Page exists: get the merged content with the proposed change
100 $baseRev = Revision
::newFromPageId( $page->getId(), $params['baserevid'] );
102 $this->dieWithError( [ 'apierror-nosuchrevid', $params['baserevid'] ] );
104 $currentRev = $page->getRevision();
105 if ( !$currentRev ) {
106 $this->dieWithError( [ 'apierror-missingrev-pageid', $page->getId() ], 'missingrev' );
108 // Merge in the new version of the section to get the proposed version
109 $editContent = $page->replaceSectionAtRev(
112 $params['sectiontitle'],
115 if ( !$editContent ) {
116 $this->dieWithError( 'apierror-sectionreplacefailed', 'replacefailed' );
118 if ( $currentRev->getId() == $baseRev->getId() ) {
119 // Base revision was still the latest; nothing to merge
120 $content = $editContent;
122 // Merge the edit into the current version
123 $baseContent = $baseRev->getContent();
124 $currentContent = $currentRev->getContent();
125 if ( !$baseContent ||
!$currentContent ) {
126 $this->dieWithError( [ 'apierror-missingcontent-pageid', $page->getId() ], 'missingrev' );
128 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
129 $content = $handler->merge3( $baseContent, $editContent, $currentContent );
132 // New pages: use the user-provided content model
133 $content = $textContent;
136 if ( !$content ) { // merge3() failed
137 $this->getResult()->addValue( null,
138 $this->getModuleName(), [ 'status' => 'editconflict' ] );
142 // The user will abort the AJAX request by pressing "save", so ignore that
143 ignore_user_abort( true );
145 if ( $user->pingLimiter( 'stashedit' ) ) {
146 $status = 'ratelimited';
148 $status = self
::parseAndStash( $page, $content, $user, $params['summary'] );
149 $textKey = $cache->makeKey( 'stashedit', 'text', $textHash );
150 $cache->set( $textKey, $text, self
::MAX_CACHE_TTL
);
153 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
154 $stats->increment( "editstash.cache_stores.$status" );
156 $ret = [ 'status' => $status ];
157 // If we were rate-limited, we still return the pre-existing valid hash if one was passed
158 if ( $status !== 'ratelimited' ||
$params['stashedtexthash'] !== null ) {
159 $ret['texthash'] = $textHash;
162 $this->getResult()->addValue( null, $this->getModuleName(), $ret );
166 * @param WikiPage $page
167 * @param Content $content Edit content
169 * @param string $summary Edit summary
170 * @return string ApiStashEdit::ERROR_* constant
173 public static function parseAndStash( WikiPage
$page, Content
$content, User
$user, $summary ) {
174 $logger = LoggerFactory
::getInstance( 'StashEdit' );
176 $title = $page->getTitle();
177 $key = self
::getStashKey( $title, self
::getContentHash( $content ), $user );
180 // Use the master DB to allow for fast blocking locks on the "save path" where this
181 // value might actually be used to complete a page edit. If the edit submission request
182 // happens before this edit stash requests finishes, then the submission will block until
183 // the stash request finishes parsing. For the lock acquisition below, there is not much
184 // need to duplicate parsing of the same content/user/summary bundle, so try to avoid
185 // blocking at all here.
186 $dbw = wfGetDB( DB_MASTER
);
187 if ( !$dbw->lock( $key, $fname, 0 ) ) {
188 // De-duplicate requests on the same key
189 return self
::ERROR_BUSY
;
191 /** @noinspection PhpUnusedLocalVariableInspection */
192 $unlocker = new ScopedCallback( function () use ( $dbw, $key, $fname ) {
193 $dbw->unlock( $key, $fname );
196 $cutoffTime = time() - self
::PRESUME_FRESH_TTL_SEC
;
198 // Reuse any freshly build matching edit stash cache
199 $editInfo = self
::getStashValue( $key );
200 if ( $editInfo && wfTimestamp( TS_UNIX
, $editInfo->timestamp
) >= $cutoffTime ) {
201 $alreadyCached = true;
203 $format = $content->getDefaultFormat();
204 $editInfo = $page->prepareContentForEdit( $content, null, $user, $format, false );
205 $alreadyCached = false;
208 if ( $editInfo && $editInfo->output
) {
209 // Let extensions add ParserOutput metadata or warm other caches
210 Hooks
::run( 'ParserOutputStashForEdit',
211 [ $page, $content, $editInfo->output
, $summary, $user ] );
213 $titleStr = (string)$title;
214 if ( $alreadyCached ) {
215 $logger->debug( "Already cached parser output for key '{cachekey}' ('{title}').",
216 [ 'cachekey' => $key, 'title' => $titleStr ] );
217 return self
::ERROR_NONE
;
220 $code = self
::storeStashValue(
222 $editInfo->pstContent
,
224 $editInfo->timestamp
,
228 if ( $code === true ) {
229 $logger->debug( "Cached parser output for key '{cachekey}' ('{title}').",
230 [ 'cachekey' => $key, 'title' => $titleStr ] );
231 return self
::ERROR_NONE
;
232 } elseif ( $code === 'uncacheable' ) {
234 "Uncacheable parser output for key '{cachekey}' ('{title}') [{code}].",
235 [ 'cachekey' => $key, 'title' => $titleStr, 'code' => $code ] );
236 return self
::ERROR_UNCACHEABLE
;
238 $logger->error( "Failed to cache parser output for key '{cachekey}' ('{title}').",
239 [ 'cachekey' => $key, 'title' => $titleStr, 'code' => $code ] );
240 return self
::ERROR_CACHE
;
244 return self
::ERROR_PARSE
;
248 * Check that a prepared edit is in cache and still up-to-date
250 * This method blocks if the prepared edit is already being rendered,
251 * waiting until rendering finishes before doing final validity checks.
253 * The cache is rejected if template or file changes are detected.
254 * Note that foreign template or file transclusions are not checked.
256 * The result is a map (pstContent,output,timestamp) with fields
257 * extracted directly from WikiPage::prepareContentForEdit().
259 * @param Title $title
260 * @param Content $content
261 * @param User $user User to get parser options from
262 * @return stdClass|bool Returns false on cache miss
264 public static function checkCache( Title
$title, Content
$content, User
$user ) {
265 if ( $user->isBot() ) {
266 return false; // bots never stash - don't pollute stats
269 $logger = LoggerFactory
::getInstance( 'StashEdit' );
270 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
272 $key = self
::getStashKey( $title, self
::getContentHash( $content ), $user );
273 $editInfo = self
::getStashValue( $key );
274 if ( !is_object( $editInfo ) ) {
275 $start = microtime( true );
276 // We ignore user aborts and keep parsing. Block on any prior parsing
277 // so as to use its results and make use of the time spent parsing.
278 // Skip this logic if there no master connection in case this method
279 // is called on an HTTP GET request for some reason.
280 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
281 $dbw = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
282 if ( $dbw && $dbw->lock( $key, __METHOD__
, 30 ) ) {
283 $editInfo = self
::getStashValue( $key );
284 $dbw->unlock( $key, __METHOD__
);
287 $timeMs = 1000 * max( 0, microtime( true ) - $start );
288 $stats->timing( 'editstash.lock_wait_time', $timeMs );
291 if ( !is_object( $editInfo ) ||
!$editInfo->output
) {
292 $stats->increment( 'editstash.cache_misses.no_stash' );
293 $logger->debug( "Empty cache for key '$key' ('$title'); user '{$user->getName()}'." );
297 $age = time() - wfTimestamp( TS_UNIX
, $editInfo->output
->getCacheTime() );
298 if ( $age <= self
::PRESUME_FRESH_TTL_SEC
) {
299 // Assume nothing changed in this time
300 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
301 $logger->debug( "Timestamp-based cache hit for key '$key' (age: $age sec)." );
302 } elseif ( isset( $editInfo->edits
) && $editInfo->edits
=== $user->getEditCount() ) {
303 // Logged-in user made no local upload/template edits in the meantime
304 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
305 $logger->debug( "Edit count based cache hit for key '$key' (age: $age sec)." );
306 } elseif ( $user->isAnon()
307 && self
::lastEditTime( $user ) < $editInfo->output
->getCacheTime()
309 // Logged-out user made no local upload/template edits in the meantime
310 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
311 $logger->debug( "Edit check based cache hit for key '$key' (age: $age sec)." );
313 // User may have changed included content
318 $stats->increment( 'editstash.cache_misses.proven_stale' );
319 $logger->info( "Stale cache for key '$key'; old key with outside edits. (age: $age sec)" );
320 } elseif ( $editInfo->output
->getFlag( 'vary-revision' ) ) {
321 // This can be used for the initial parse, e.g. for filters or doEditContent(),
322 // but a second parse will be triggered in doEditUpdates(). This is not optimal.
323 $logger->info( "Cache for key '$key' ('$title') has vary_revision." );
324 } elseif ( $editInfo->output
->getFlag( 'vary-revision-id' ) ) {
325 // Similar to the above if we didn't guess the ID correctly.
326 $logger->info( "Cache for key '$key' ('$title') has vary_revision_id." );
334 * @return string|null TS_MW timestamp or null
336 private static function lastEditTime( User
$user ) {
337 $db = wfGetDB( DB_REPLICA
);
338 $actorQuery = ActorMigration
::newMigration()->getWhere( $db, 'rc_user', $user, false );
339 $time = $db->selectField(
340 [ 'recentchanges' ] +
$actorQuery['tables'],
342 [ $actorQuery['conds'] ],
348 return wfTimestampOrNull( TS_MW
, $time );
352 * Get hash of the content, factoring in model/format
354 * @param Content $content
357 private static function getContentHash( Content
$content ) {
358 return sha1( implode( "\n", [
359 $content->getModel(),
360 $content->getDefaultFormat(),
361 $content->serialize( $content->getDefaultFormat() )
366 * Get the temporary prepared edit stash key for a user
368 * This key can be used for caching prepared edits provided:
369 * - a) The $user was used for PST options
370 * - b) The parser output was made from the PST using cannonical matching options
372 * @param Title $title
373 * @param string $contentHash Result of getContentHash()
374 * @param User $user User to get parser options from
377 private static function getStashKey( Title
$title, $contentHash, User
$user ) {
378 return ObjectCache
::getLocalClusterInstance()->makeKey(
380 md5( $title->getPrefixedDBkey() ),
381 // Account for the edit model/text
383 // Account for user name related variables like signatures
384 md5( $user->getId() . "\n" . $user->getName() )
389 * @param string $uuid
392 private static function getStashParserOutputKey( $uuid ) {
393 return ObjectCache
::getLocalClusterInstance()->makeKey( 'stashed-edit-output', $uuid );
398 * @return stdClass|bool Object map (pstContent,output,outputID,timestamp,edits) or false
400 private static function getStashValue( $key ) {
401 $cache = ObjectCache
::getLocalClusterInstance();
403 $stashInfo = $cache->get( $key );
404 if ( !is_object( $stashInfo ) ) {
408 $parserOutputKey = self
::getStashParserOutputKey( $stashInfo->outputID
);
409 $parserOutput = $cache->get( $parserOutputKey );
410 if ( $parserOutput instanceof ParserOutput
) {
411 $stashInfo->output
= $parserOutput;
420 * Build a value to store in memcached based on the PST content and parser output
422 * This makes a simple version of WikiPage::prepareContentForEdit() as stash info
425 * @param Content $pstContent Pre-Save transformed content
426 * @param ParserOutput $parserOutput
427 * @param string $timestamp TS_MW
429 * @return string|bool True or an error code
431 private static function storeStashValue(
432 $key, Content
$pstContent, ParserOutput
$parserOutput, $timestamp, User
$user
434 // If an item is renewed, mind the cache TTL determined by config and parser functions.
435 // Put an upper limit on the TTL for sanity to avoid extreme template/file staleness.
436 $age = time() - wfTimestamp( TS_UNIX
, $parserOutput->getCacheTime() );
437 $ttl = min( $parserOutput->getCacheExpiry() - $age, self
::MAX_CACHE_TTL
);
438 // Avoid extremely stale user signature timestamps (T84843)
439 if ( $parserOutput->getFlag( 'user-signature' ) ) {
440 $ttl = min( $ttl, self
::MAX_SIGNATURE_TTL
);
444 return 'uncacheable'; // low TTL due to a tag, magic word, or signature?
447 // Store what is actually needed and split the output into another key (T204742)
448 $parseroutputID = md5( $key );
449 $stashInfo = (object)[
450 'pstContent' => $pstContent,
451 'outputID' => $parseroutputID,
452 'timestamp' => $timestamp,
453 'edits' => $user->getEditCount()
456 $cache = ObjectCache
::getLocalClusterInstance();
457 $ok = $cache->set( $key, $stashInfo, $ttl );
460 self
::getStashParserOutputKey( $parseroutputID ),
467 // These blobs can waste slots in low cardinality memcached slabs
468 self
::pruneExcessStashedEntries( $cache, $user, $key );
471 return $ok ?
true : 'store_error';
475 * @param BagOStuff $cache
477 * @param string $newKey
479 private static function pruneExcessStashedEntries( BagOStuff
$cache, User
$user, $newKey ) {
480 $key = $cache->makeKey( 'stash-edit-recent', $user->getId() );
482 $keyList = $cache->get( $key ) ?
: [];
483 if ( count( $keyList ) >= self
::MAX_CACHE_RECENT
) {
484 $oldestKey = array_shift( $keyList );
485 $cache->delete( $oldestKey );
488 $keyList[] = $newKey;
489 $cache->set( $key, $keyList, 2 * self
::MAX_CACHE_TTL
);
492 public function getAllowedParams() {
495 ApiBase
::PARAM_TYPE
=> 'string',
496 ApiBase
::PARAM_REQUIRED
=> true
499 ApiBase
::PARAM_TYPE
=> 'string',
502 ApiBase
::PARAM_TYPE
=> 'string'
505 ApiBase
::PARAM_TYPE
=> 'text',
506 ApiBase
::PARAM_DFLT
=> null
508 'stashedtexthash' => [
509 ApiBase
::PARAM_TYPE
=> 'string',
510 ApiBase
::PARAM_DFLT
=> null
513 ApiBase
::PARAM_TYPE
=> 'string',
516 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
517 ApiBase
::PARAM_REQUIRED
=> true
520 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
521 ApiBase
::PARAM_REQUIRED
=> true
524 ApiBase
::PARAM_TYPE
=> 'integer',
525 ApiBase
::PARAM_REQUIRED
=> true
530 public function needsToken() {
534 public function mustBePosted() {
538 public function isWriteMode() {
542 public function isInternal() {